
/*
 * @Author: sdorein sdorein@163.com
 * @Date: 2024-09-09 17:13:10
 * @LastEditors: sdorein sdorein@163.com
 * @LastEditTime: 2024-10-30 16:31:40
 * @FilePath: \vite-web\src\api\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse ,InternalAxiosRequestConfig} from 'axios';
// @ts-expect-error
import { console } from 'inspector';

class HttpService {
  private instance: AxiosInstance;

  constructor(baseURL: string) {
    this.instance = axios.create({
      baseURL,
      timeout: 10000,
    });

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        // 可以在这里添加请求头、token 等
        const token = localStorage.getItem('token');
        if (token) {
          config.headers = {
            Authorization: `Bearer ${token}`,
          };
        }
        const newConfig = config as unknown as InternalAxiosRequestConfig<any>;
        return newConfig;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        return response.data;
      },
      (error) => {
        // 可以在这里统一处理错误响应
        return Promise.reject(error);
      }
    );
  }

  async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.instance.get(url, config);
    return response as T;
  }

  async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.instance.post(url, data, config);
    return response.data as T;
  }

  // 可以继续添加其他请求方法如 put、delete 等
}

export default HttpService;